/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.protocol;

import java.util.Hashtable;

import cgl.narada.util.ByteUtilities;
/**
 * The protocol layers deal only with the logical addresses associated with the
 * nodes (be they clients or servers). This class maintains information 
 * regarding a nodes address. Utilitiy functions include accessor functions
 * which can get information regarding a nodes address in terms of bytes or
 * ints. 
 *
 * @author Shrideep Pallickara
 * $Revision$
 * $Date$
 */


public class NodeAddress implements ProtocolDebugFlags {

  private byte[] addressInBytes;
  private int[] addressInInts;
  private boolean clientAddress=false;

  public NodeAddress(byte[] addressInBytes) {
    this.addressInBytes = addressInBytes;
    addressInInts  = transformByteAddress(addressInBytes);
  }
  
  public NodeAddress(int[] addressInInts) {
    this.addressInInts = addressInInts;
    addressInBytes = transformIntAddress(addressInInts);
  }

  /**This is to construct a node address specific to client connections.*/
  public NodeAddress(byte[] addressInBytes, boolean isClientAddress) {
    clientAddress = isClientAddress;
    this.addressInBytes = addressInBytes;
    addressInInts = new int[1];
    addressInInts[0] = ByteUtilities.getInt(addressInBytes);
  }
  
  /** Accessor function to get the node address as a sequence of bytes 
      @return A byte[] of the node's address*/
  public byte[] getAddressInBytes() {
    return addressInBytes;
  }
  
  /** Accessor function to get the node address as a sequence of ints 
   @return An int[] of the node's address*/
  public int[] getAddressInInts() {
    return addressInInts;
  }

  /**
     Compares two objects for equality. Returns a boolean that indicates
     whether this object is equivalent to the specified object. This method
     is used when an object is stored in a hashtable.
     @param obj the Object to compare with
     @return true if these Objects are equal; false otherwise.
     @see java.util.Hashtable
  */
  public boolean equals(Object obj) {
    int[] addressIntsObj = ((NodeAddress)obj).getAddressInInts();
    if (addressIntsObj.length != addressInInts.length) {
      return false;
    }
    for (int i=0; i<addressInInts.length; i++) {
      if (addressIntsObj[i] != addressInInts[i]) {
	return false;
      }
    }
    return true;
  }
  
  /**
     Generates a hash code for the receiver. This method is supported 
     primarily for hash tables, such as those provided in java.util.
     If two objects are equal (equals(Object) returns true) they must have the 
     same hash code
     @return an integer hash code for the receiver 
  */
  public int hashCode() {
    int code=1;
    for (int i=0; i < addressInInts.length; i++) {
      code*= addressInInts[i];
    }
    return  code;
     //addressInInts.hashCode();
  }
  
  /** Utility method which transforms our address in ints to an appropriately
      constructed byte[] 
      @param intArray the integer array of the node's address
      @return a byte[] representation of the node's address
  */
  private byte[] transformIntAddress(int[] intArray) {
    int inputArrayLength = intArray.length;
    byte[] byteArray = new byte[inputArrayLength*4];
    
    for (int i=0; i< inputArrayLength; i++) {
      if (intArray[i] <= 8) {
	byteArray[4*i +3] = 1;
	byteArray[4*i +3] <<= (intArray[i]-1);
      } 
      if (intArray[i] > 8 && intArray[i] <= 16) {
	byteArray[4*i +2] = 1;
	byteArray[4*i +2] <<= (intArray[i]-8-1);
      }
      if (intArray[i] > 16 && intArray[i] <= 24) {
	byteArray[4*i +1] = 1;
	byteArray[4*i +1] <<= (intArray[i]-16-1);
      }
      if (intArray[i] > 24 && intArray[i] <= 32) {
	byteArray[4*i] = 1;
	byteArray[4*i] <<= (intArray[i]-24-1);
      }      
    }
    return byteArray;
  }
  
  /** Utility method which transforms our address in bytes to an appropriately
      constructed int[] 
      @param byteArray the integer array of the node's address
      @return an int[] representation of the node's address
  */
  private int[] transformByteAddress(byte[] byteArray) {
    int inputArrayLength = byteArray.length;
    /** 4 "bytes" in our node address scheme comprise an "int" in the 
	corresponding integer addressing scheme */
    if (inputArrayLength%2 !=0) {
      System.out.println("NodeAddress :: Messed up integer array address");
    }
    int[] intArray = new int[inputArrayLength/4];
    for (int i=0; i < inputArrayLength/4; i++) {
      if (byteArray[4*i +3] != 0 ) {
	intArray[i] = getValue(byteArray[4*i +3]);
      }
      if (byteArray[4*i +2] != 0 ) {
	intArray[i] = getValue(byteArray[4*i +2]) +8;
      }
      if (byteArray[4*i +1] != 0 ) {
	intArray[i] = getValue(byteArray[4*i +1]) +16;
      }
      if (byteArray[4*i] != 0 ) {
	intArray[i] = getValue(byteArray[4*i]) +24;
      }
    }
    return intArray;
  }
  
  private int getValue(byte b) {
    int value =1;
    int num = b;
    if (num <0) return 8;
    num >>>= 1;
    while ( num !=0) {
      value++;
       num >>>=1;
    }
    return value;
  }
  
  /** This method is implemented to enable a System.out.println() on the
      node's address. The string returned provides the node's logical address
      as a sequence of bytes (with each bit represented).
  */
  public String toString() {
    String val = "{ ";
    /*for (int i=0; i <addressInBytes.length/4; i++) {
      val = val + ByteUtilities.printByte(addressInBytes[4*i]) +  
      ByteUtilities.printByte(addressInBytes[4*i +1]) + 
      ByteUtilities.printByte(addressInBytes[4*i +2]) + 
      ByteUtilities.printByte(addressInBytes[4*i +3]) + " " ;
      }*/
    for (int i=0; i <addressInInts.length; i++) {
      val = val + addressInInts[i] + " ";
    }
    return val + "}";
  }

  public static void main(String[] args) {
    int[] address = {5, 8, 15, 31};
    int [] address2 = {4,8,15,31};
    NodeAddress nodeAddress = new NodeAddress(address);
    byte[] addressBytes = nodeAddress.getAddressInBytes();

    for (int i=0; i <addressBytes.length/4; i++) {
      System.out.print(new Byte(addressBytes[4*i]));
       System.out.print(new Byte(addressBytes[4*i +1]));
        System.out.print(new Byte(addressBytes[4*i +2]));
      System.out.println(addressBytes[4*i +3]);
    }
    System.out.println("Reverse Testing results ..");
    nodeAddress = new NodeAddress(addressBytes);
    int[] addressInts = nodeAddress.getAddressInInts();
    System.out.print("{");
    for (int i=0; i < 4; i++) {
      System.out.print(" " +addressInts[i] + ",");
    }
    System.out.println("}");

    NodeAddress nodeAddress2 = new NodeAddress(address2);
    Hashtable hashtable = new Hashtable();
    String val1 = "The first Address";
    String val2 = "The second Address";
    hashtable.put(nodeAddress, val1);
    hashtable.put(nodeAddress2, val2);
    System.out.println(nodeAddress);
    System.out.println("Disriminating the secondAddress with " +
		       " hashtable.get(nodeAddress2) " +
		       hashtable.get(nodeAddress2));
    int clientId = 1000;
    byte[] destinationBytes = new byte[4];
    destinationBytes = ByteUtilities.getBytes(clientId);
    NodeAddress node1 = new NodeAddress(destinationBytes, true);
    destinationBytes = ByteUtilities.getBytes(++clientId);
    NodeAddress node2 = new NodeAddress(destinationBytes, true);
    System.out.println(node1);
    System.out.println(node2);
  }
}

